import useHotKey from '@/hooks/useHotKey'
import { editorInfos } from '@/stores/editor'
import pinia from '@/stores/index'
import type { HotkeysEvent, KeyHandler } from 'hotkeys-js'
import { computed } from 'vue'

const wrap = (callback: KeyHandler) => {
  const wrapperFn = (e: KeyboardEvent, event: HotkeysEvent) => {
    e.preventDefault()
    callback(e, event)
  }
  return wrapperFn
}
export default function initHotKeys() {
  const editorStore = editorInfos(pinia)
  const currentId = computed(() => editorStore.currentElement)
  useHotKey('ctrl+c, command+c', () => {
    editorStore.copyComponent(currentId.value)
  })
  useHotKey('ctrl+v, command+v', () => {
    editorStore.pasteCopiedComponent()
  })
  useHotKey('backspace, delete', () => {
    editorStore.deleteComponent(currentId.value)
  })

  useHotKey('Ctrl+Z', () => {
    editorStore.undo()
  })
  useHotKey('Ctrl+Shift+Z', () => {
    editorStore.redo()
  })
  useHotKey('esc', () => {
    editorStore.setActive('')
  })
  useHotKey(
    'up',
    wrap(() => {
      editorStore.moveComponent({ direction: 'Up', amount: 1, id: currentId.value })
    })
  )
  useHotKey(
    'down',
    wrap(() => {
      editorStore.moveComponent({ direction: 'Down', amount: 1, id: currentId.value })
    })
  )
  useHotKey(
    'left',
    wrap(() => {
      editorStore.moveComponent({ direction: 'Left', amount: 1, id: currentId.value })
    })
  )
  useHotKey(
    'right',
    wrap(() => {
      editorStore.moveComponent({ direction: 'Right', amount: 1, id: currentId.value })
    })
  )
}
